package cn.harry.modular.sys.controller;

import cn.harry.common.annotation.SysLog;
import cn.harry.common.api.R;
import cn.harry.common.enums.BusinessType;
import cn.harry.modular.sys.domain.SysDictDetail;
import cn.harry.modular.sys.enums.CacheConstants;
import cn.harry.modular.sys.service.SysDictDetailService;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 数据字典详情详情详情
 *
 * @author honghh Date 2020-03-16 09:53:38 Copyright (C) www.tech-harry.cn
 */
@Slf4j
@Tag(name = "sys-dict-detail => 字典详情管理")
@RestController
@RequiredArgsConstructor
@RequestMapping("sys/dict/detail")
public class SysDictDetailController {

    private final SysDictDetailService sysDictDetailService;

    @Operation(summary = "dictType/{dictType} 根据字典类型查询字典详情数据信息")
    @GetMapping(value = "/dictType/{dictType}")
    @Cacheable(value = CacheConstants.DICT_DETAILS, key = "#dictType")
    public R<List<SysDictDetail>> dictType(@PathVariable String dictType) {
        return R.success(sysDictDetailService.selectDictDataByType(dictType));
    }

    @Operation(summary = "list 分页列表")
    @Parameters({
            @Parameter(name = "current", description = "当前页", required = true, example = "1"),
            @Parameter(name = "size", description = "每页显示条数", required = true, example = "10")
    })
    @PreAuthorize("@ss.hasPermission('system:dict:list')")
    @GetMapping(value = "/list")
    public R<IPage<SysDictDetail>> list(@Parameter(hidden = true) Page<SysDictDetail> page,
                                        SysDictDetail dictDetail) {
        return R.success(
                sysDictDetailService.page(page, Wrappers.lambdaQuery(dictDetail)));
    }

    @Operation(summary = "{id} 根据ID获取详细信息")
    @PreAuthorize("@ss.hasPermission('system:dict:query')")
    @GetMapping(value = "/{id}")
    public R<SysDictDetail> getInfo(@PathVariable Long id) {
        return R.success(sysDictDetailService.getById(id));
    }

    @Operation(summary = "新增")
    @PreAuthorize("@ss.hasPermission('system:dict:add')")
    @SysLog(title = "字典类型", businessType = BusinessType.INSERT)
    @PostMapping
    @CacheEvict(value = CacheConstants.DICT_DETAILS, key = "#dictDetail.dictType")
    public R<Integer> create(@RequestBody SysDictDetail dictDetail) {
        return sysDictDetailService.save(dictDetail) ? R.success() : R.failed();
    }

    @Operation(summary = "更新")
    @PreAuthorize("@ss.hasPermission('system:dict:edit')")
    @SysLog(title = "字典类型", businessType = BusinessType.UPDATE)
    @PutMapping
    @CacheEvict(value = CacheConstants.DICT_DETAILS, key = "#dictDetail.dictType")
    public R<Integer> update(@RequestBody SysDictDetail dictDetail) {
        return sysDictDetailService.updateById(dictDetail) ? R.success() : R.failed();
    }

    @Operation(summary = "删除")
    @PreAuthorize("@ss.hasPermission('system:dict:remove')")
    @SysLog(title = "字典类型", businessType = BusinessType.DELETE)
    @DeleteMapping(value = "/{ids}")
    public R<Integer> deleteByIds(@Parameter(description = "多个以英文逗号(,)拼接") @PathVariable Long[] ids) {
        return sysDictDetailService.removeBatchByIds(Arrays.asList(ids)) ? R.success()
                : R.failed();
    }

    @Operation(summary = "export 导出")
    @PreAuthorize("@ss.hasPermission('system:dict:export')")
    @SysLog(title = "字典类型", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public R export(HttpServletResponse response, SysDictDetail dictDetail) {
        List<SysDictDetail> list = sysDictDetailService.getExportList(dictDetail);
        try {
            EasyExcel.write(response.getOutputStream(), SysDictDetail.class).sheet("字典类型")
                    .doWrite(list);
            return R.success();
        } catch (IOException e) {
            log.error("字典详情管理,导出失败 error:{}", e.getMessage());
        }
        return R.failed();
    }

}
